using System;
using System.Reflection;
using Baula.TextGen.Framework.ComInterop;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Baula.TextGen.Framework.Tests.Exceptions
{
    [TestClass]
    public class TextGenExceptionTests
    {
        [TestMethod]
        public void UnknownPartNameException_WhenThrown_GivesSpecialHResult()
        {
            try
            {
                throw new UnknownPartNameException("Unknown part name");
            }
            catch (UnknownPartNameException xcp)
            {
                var hResult = GetHResult(xcp);
                Assert.AreEqual((int)ErrorCodes.UnknownPartName, hResult);
            }
            catch (Exception)
            {
                Assert.Fail("A wrong exception has been thrown.");
            }
        }

        [TestMethod]
        public void UnknownPartNameException_WhenThrown_GivesCorrectMessage()
        {
            try
            {
                throw new UnknownPartNameException("UnknownPartName");
            }
            catch (UnknownPartNameException xcp)
            {
                Assert.AreEqual("There is no part template named \"UnknownPartName\".", xcp.Message);
            }
            catch (Exception)
            {
                Assert.Fail("A wrong exception has been thrown.");
            }
        }

        private object GetHResult(Exception xcp)
        {
            return GetPrivatePropertyValue(xcp, "HResult");
        }

        private object GetPrivatePropertyValue(object instance, string propertyName)
        {
            return instance.GetType()
                .GetProperty(propertyName, BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance)
                .GetValue(instance, null);
        }
    }
}